import webapp2
from model.Users import TodoUser
import logging
import json
from webapp2_extras import jinja2

jinja2.default_config['template_path'] = 'htmlTemplates'

class Users(webapp2.RequestHandler):
    def get(self):
        self.displayUsers()
        
    def delete(self):
        logging.info('delete Users')
        data = self.request.body
        logging.info('data: '+data)
        if not data:
            logging.info('no data')
        else:
            entity = json.loads(data)
            theKey = entity["key"];
            logging.info('theKey: '+theKey)                  
            intId = int(theKey)
            theUser = TodoUser.get_by_id(intId)
            
#        theUser.delete()
            self.response.content_type='application/json'
            self.response.out.write(json.dumps('{method:"DELETE",id:"'+theKey+'"}'));   
    
    def put(self):
        logging.info('put Users')
        theUserName = self.request.get('key')
        logging.info('theUserName: '+theUserName)
        data = self.request.body
        logging.info('data: '+data)
        if not data:
            logging.info('no data')
        else:
            entity = json.loads(data)
            theKey = entity["key"];
            logging.info('theKey: '+theKey)
#        thePwd = self.request.get('pwd')
#        userId = self.request.get('userId')
#        toDoUser = TodoUser(id=userId, pwd=thePwd, userName=theUserName)
#        toDoUser.put()
        self.displayUsers()
    
    def post(self):
        logging.info('post Users')
        self.displayUsers()
        
    def displayUsers(self):
        todoUsers = TodoUser.all()
        logging.info('todoUsers.count: '+str(todoUsers.count()))
        values = {
            'todoUsers': todoUsers,
            'numberTodoUsers' : todoUsers.count()
        }
        for aUser in todoUsers:
            logging.info(aUser.userName)
            logging.info(aUser.id)
            logging.info(aUser.key().id())
#        _jinja2.render_template('htmlTemplate/Users.html', values)
#        self.response.out.write(template.render('htmlTemplate/Users.html', values))
        self._render_response('Users.html', **values)

    @webapp2.cached_property
    def _jinja2(self):
        # Returns a Jinja2 renderer cached in the app registry.
        return jinja2.get_jinja2(app=self.app)

    def _render_response(self, _template, **context):
        # Renders a template and writes the result to the response.
        rv = self._jinja2.render_template(_template, **context)
        self.response.write(rv)



# Register the URL with the responsible classes
application = webapp2.WSGIApplication(
            [
             ('/users',Users)
            ],
            debug=True
        )